<?
class gCsv extends gravy{

	public $header=array();
	public $data=array();
	public $dataTypes=array();
	public $text="";
	public $escapeWith="\"";
	public $lineBreak="\n";
	public $encloseFields="\"";
	public $separator=",";
	public $includeHeaderRow=true;

	public function __construct($header=NULL,$data=NULL){
		$this->header=($header===NULL)?array():$header;
		$this->data=($data===NULL)?array():$data;
	}

	public function setHeader($ar){
		$this->header=$ar;
	}

	public function setHeaderItem($value){
		$this->header[]=$value;
	}

	public function addRow($ar){
		$this->data[]=$ar;
	}

	public function setData($ar){
		$this->data=$ar;
	}

	public function addRowItem($index,$key,$value){
		$this->data[$index][$key]=$value;
	}

	public function getCsvData(){
		$this->text="";
		if($this->includeHeaderRow){
			for($c=0;$c<count($this->header);$c++){
				if(strpos($this->header[$c],",")>-1){
					$this->text.=$this->encloseFields.$this->header[$c].$this->encloseFields;
				}else{
					$this->text.=$this->header[$c];
				}
				$this->text.=",";
			}
			$this->text=substr($this->text,0,strlen($this->text)-1).$this->lineBreak;
		}
		for($c=0;$c<count($this->data);$c++){
			$row=$this->data[$c];
			$i=0;
			foreach($row as $key=>$val){
				$enclose=(strtolower($this->dataTypes[$key])=="string");
				if(((preg_match("/[a-zA-Z,]+/",$val)>0&&strtolower($val)!="true"&&strtolower($val)!="false")||$enclose)&&strlen($val)>0){
					$this->text.=$this->encloseFields.str_replace("\"",$this->escape."\"",$val).$this->encloseFields.",";
				}else{
					$this->text.=$val.",";
				}
				$i++;
			}
			$this->text=substr($this->text,0,strlen($this->text)-1).$this->lineBreak;
		}
		return($this->text);
	}

	public function save($file=NULL,$data=NULL){
		$file=($file===NULL)?"csv-file_".date("Ymdhis",time()).".csv":$file;
		if($data!==NULL){
			$this->setData($data);
		}
		$text=$this->getCsvData();
		return(@file_put_contents($file,$text));
	}

	public function output($file=NULL,$data=NULL){
		$file=($file===NULL)?"csv-file_".date("Ymdhis",time()).".csv":$file;
		if($data!==NULL){
			$this->setData($data);
		}
		$text=$this->getCsvData();
		header("content-type:application/csv\n\n");
		header("content-disposition:attachment;filename=".$file.";\n\n");
		header("Pragma: no-cache;\n\n");
		header("Expires: 0;\n\n");
		print($text);
	}
}
?>